# from django.test import TestCase
#
# # Create your tests here.
#
# 从docx获取图片并保存到本地图片或者本地pdf
# from docx import Document
# from PIL import Image
# import os
# import io
# import re
# from xpinyin import Pinyin
# import img2pdf
# from docx.shared import Inches
# from docx.enum.section import WD_SECTION
#
# def extract_chinese(text):
#     # 使用正则表达式匹配中文字符，\u4e00-\u9fff是中文字符的Unicode编码范围
#     chinese_chars = re.findall(r'[\u4e00-\u9fff]+', text)
#     return ''.join(chinese_chars)
#
# #获取序号后的文本
# def get_content(text):
#     # index = 0
#     # for i,char in enumerate(text):
#     #     if '\u4e00' <= char <= '\u9fff':
#     #         index = i
#     #         break
#     # return text[index:].replace('\t','').replace('\n','').replace(' ','')
#     return text.replace('\t','').replace('\n','').replace(' ','')
#
# doc = Document('/media/977GB/virtualbox/转图片的word/验收报告.docx')
# folder = '/media/977GB/virtualbox/word转图片'
#
# p = Pinyin()
# index = 1
#
# res = {}
#
# title = ''
# subtitle = ''
#
# for element in doc.element.body:
#     if element.tag.endswith('p'):
#         if 'docPr' in element.xml:
#             rids = re.findall(r"rId\d+", element.xml)
#             for rid in rids:
#                 # 打印所有匹配的子串
#                 img_name = f'图片{index}'
#                 index += 1
#                 # rid = re.findall(r"rId\d+", element.xml)[0]
#                 # print([title,subtitle])
#                 # res[title][subtitle].append([rid,img_name])
#                 res[title][subtitle].append(rid)
#         else:
#
#             text = get_content(element.text)
#             print(text)
#             if text:
#                 judge = True
#                 # for i in ['中标通知书','合同扫描件','合同转签协议','验收证书','合同关键页','企业名称变更备案']:
#                 for i in ['学历证书','资格证书','社保']:
#                     if i in text:
#                         res[title][text] = []
#                         subtitle = text
#                         judge = False
#                         break
#                 if judge:
#                     title = text
#                     res[title] = {}
#
# #所有图片
# imgs = doc.part.related_parts
# # a = {}
# # a['14.7.客户服务平台二期(营销管理系统业扩升级改造)建设项目'] = res['14.7.客户服务平台二期(营销管理系统业扩升级改造)建设项目']
#
# i = 0
# l = len(res)
# _id = 37
# s = 0
#
# for key,value in res.items():
#
#     i += 1
#     # print(f'//////////////////////////////////{i}/{l}')
#     #创建文件夹
#     sub_folder = os.path.join(folder,f"{p.get_pinyin(key,'')}_{key}")
#     if not os.path.isdir(sub_folder):
#         os.makedirs(sub_folder)
#     for sub_key,sub_value in value.items():
#         if len(sub_value) == 1:
#             file_path = f"{os.path.join(sub_folder,sub_key)}.png"
#             f = open(file_path, 'wb')
#             img = imgs[sub_value[0]]
#             f.write(img.blob)
#             f.close()
#             # save_sql_path = f"{os.path.join(sub_folder,sub_key)}.png"
#             # _type = 'img'
#         else:
#             if sub_key == '社保证明':
#
#                 for rid, year in zip(sub_value,['202503','202502','202501']):
#                     file_path = f"{os.path.join(sub_folder, sub_key)}_{year}.png"
#                     f = open(file_path, 'wb')
#                     img = imgs[rid]
#                     f.write(img.blob)
#                     f.close()
#             else:
#
#                 save_path = os.path.join(sub_folder, sub_key) + '.pdf'
#
#                 # 创建一个用于存储转换后的PDF数据的列表
#                 pdf_bytes = []
#
#                 # 从字节流加载所有图片并存储到列表中
#                 for rid in sub_value:
#                     img = imgs[rid]
#                     # 使用BytesIO读取BLOB数据
#                     img_buffer = io.BytesIO(img.blob)
#
#                     # 使用Pillow打开图片以验证其格式并进行必要的转换
#                     with Image.open(img_buffer) as img:
#                         # 如果图像不是RGB模式，则转换之
#                         if img.mode != "RGB":
#                             img = img.convert("RGB")
#
#                         # 将图像保存到一个新的BytesIO对象中，格式化为JPEG
#                         img_byte_arr = io.BytesIO()
#                         img.save(img_byte_arr, format='JPEG')
#                         img_byte_arr = img_byte_arr.getvalue()
#
#                         # 添加到PDF字节列表中
#                         pdf_bytes.append(img_byte_arr)
#                     img_buffer.close()  # 确保关闭BytesIO缓冲区
#
#                     # 使用img2pdf将所有图像合并成一个PDF
#                 with open(save_path, "wb") as f:
#                     f.write(img2pdf.convert(pdf_bytes))
#             # new_doc = Document()
#             # for rid in sub_value:
#             #     img = imgs[rid]
#             #     byte_stream = io.BytesIO(img.blob)
#             #     new_doc.add_picture(byte_stream,width=Inches(6))  # 设置图片宽度为4英寸
#             #     # 插入分页符，确保下一张图片从新页开始
#             #     new_doc.add_page_break()
#             # save_path = os.path.join(sub_folder,sub_key)+'.docx'
#             # new_doc.save(save_path)
#             # os.system(f"soffice --headless --convert-to pdf --outdir '{sub_folder}' '{save_path}'")
#             # os.remove(save_path)
#             # save_sql_path = os.path.join(sub_folder,sub_key)+'.pdf'
#             # _type = 'pdf'
#
#         #sql语句
#         # s+=1
#         # print(f"insert into ex_file (objectType,objectId,path,type,comment,uploadDate) values "
#         #           f"('project',{_id},'{save_sql_path}','{_type}','{sub_key}','2025-02-17 17:29:00');")
#
#     _id += 1
# print(s)
# 从docx获取图片并保存到本地图片或者本地pdf，只有一层，标题+图片
# import time
#
# from docx import Document
# from PIL import Image
# import os
# import io
# import re
# import img2pdf
# from docx.shared import Inches
# from docx.enum.section import WD_SECTION
#
# def extract_chinese(text):
#     # 使用正则表达式匹配中文字符，\u4e00-\u9fff是中文字符的Unicode编码范围
#     chinese_chars = re.findall(r'[\u4e00-\u9fff]+', text)
#     return ''.join(chinese_chars)
#
# #获取序号后的文本
# def get_content(text):
#     # index = 0
#     # for i,char in enumerate(text):
#     #     if '\u4e00' <= char <= '\u9fff':
#     #         index = i
#     #         break
#     # return text[index:].replace('\t','').replace('\n','').replace(' ','')
#     return text.replace('\t','').replace('\n','').replace(' ','')
#
# save_root_folder = '/media/977GB/virtualbox/word转图片'
# word_folder = '/media/977GB/virtualbox/转图片的word'
# files = os.listdir(word_folder)
#
# for file_index, file in enumerate(files, start=1):
#     doc = Document(os.path.join(word_folder, file))
#     save_folder = os.path.join(save_root_folder, os.path.splitext(file)[0])
#
#     index = 1
#
#     res = {}
#
#     title = ''
#
#     for element in doc.element.body:
#         if element.tag.endswith('p'):
#             if 'docPr' in element.xml:
#                 rids = re.findall(r"rId\d+", element.xml)
#                 # print([title,subtitle])
#                 # res[title][subtitle].append([rid,img_name])
#                 if title:
#                     for rid in rids:
#                         # 打印所有匹配的子串
#                         img_name = f'图片{index}'
#                         index += 1
#                         res[title].append(rid)
#             else:
#                 text = get_content(element.text)
#                 if text:
#                     title = text
#                     res[title] = []
#
#     #所有图片
#     imgs = doc.part.related_parts
#
#     # a = {}
#     # a['14.7.客户服务平台二期(营销管理系统业扩升级改造)建设项目'] = res['14.7.客户服务平台二期(营销管理系统业扩升级改造)建设项目']
#
#     i = 0
#     l = len(res)
#
#     for key,value in res.items():
#
#         if not value:
#             continue
#
#         i += 1
#         print(f'===========================图片：{i}/{l}\t文件：{file_index}/{len(files)}")')
#         #创建文件夹
#         sub_folder = save_folder
#         if not os.path.isdir(sub_folder):
#             os.makedirs(sub_folder)
#         if len(value) == 1:
#             file_path = f"{os.path.join(sub_folder,key)}.png"
#             f = open(file_path, 'wb')
#             img = imgs[value[0]]
#             f.write(img.blob)
#             f.close()
#             save_sql_path = f"{os.path.join(sub_folder,key)}.png"
#             _type = 'img'
#         else:
#
#             save_path = os.path.join(sub_folder, key) + '.pdf'
#
#             # 创建一个用于存储转换后的PDF数据的列表
#             pdf_bytes = []
#
#             # 从字节流加载所有图片并存储到列表中
#             for rid in value:
#                 img = imgs[rid]
#                 # 使用BytesIO读取BLOB数据
#                 img_buffer = io.BytesIO(img.blob)
#
#                 # 使用Pillow打开图片以验证其格式并进行必要的转换
#                 with Image.open(img_buffer) as img:
#                     # 如果图像不是RGB模式，则转换之
#                     if img.mode != "RGB":
#                         img = img.convert("RGB")
#
#                     # 将图像保存到一个新的BytesIO对象中，格式化为JPEG
#                     img_byte_arr = io.BytesIO()
#                     img.save(img_byte_arr, format='JPEG')
#                     img_byte_arr = img_byte_arr.getvalue()
#
#                     # 添加到PDF字节列表中
#                     pdf_bytes.append(img_byte_arr)
#                 img_buffer.close()  # 确保关闭BytesIO缓冲区
#
#                 # 使用img2pdf将所有图像合并成一个PDF
#             with open(save_path, "wb") as f:
#                 f.write(img2pdf.convert(pdf_bytes))

#
# # for i in range(74,83):
# #     print(f"insert into ex_bidPmProject (bid,project) values "
# #                       f"(1,{i});")
#
#
# # 获取表结构
# import os
# import pymysql
#
# def db_connet():
#     conn = pymysql.connect(
#         host='127.0.0.1',  # 连接名称，默认127.0.0.1
#         user='root',  # 用户名
#         passwd='123456',  # 密码
#         port=3306,  # 端口，默认为3306
#         db='zentao',  # 数据库名称
#         charset='utf8',  # 字符编码
#     )
#     print("----数据库连接成功------", conn)
#     return conn
#
# def search_db():
#     import datetime
#
#     # 获取当前时间
#     now = datetime.datetime.now()
#     f_path = './data_out/'
#     if not os.path.exists(f_path):
#         os.mkdir(f_path)
#     # 将时间格式化为字符串，例如：2025-03-11_14-30-00
#     file_name = now.strftime(f_path + "output_%Y-%m-%d_%H-%M-%S.txt")
#
#     # 使用格式化后的文件名打开文件
#     file = open(file_name, 'w', encoding='utf-8')
#     # file=open('./data_out/output.txt', 'w', encoding='utf-8')
#     # 获取游标
#     conn = db_connet()
#     cursor = conn.cursor()
#
#     # 指定要查询的表格列表
#     # table_names = [
#     #     'ex_project',
#     #     'ex_file'
#     # ]
#     table_names = {
#         'ex_project': '公司业绩基本信息表',
#         'ex_file': '附件信息表',
#         "ex_bid": " ",
#         "ex_bidPmProject": '',
#         "ex_bidProject": '',
#         "ex_bidSocialInsurance": '',
#         "ex_bidTeam": '',
#         "ex_company": '',
#         "ex_dept": '',
#         "ex_team": "",
#         "ex_teamProject": '',
#         "ex_teamQualification": '',
#         "ex_teamWork": ''
#
#     }
#
#     # 构造SQL查询，获取指定表的表名、字段名和字段备注
#     # sql = """
#     # SELECT TABLE_NAME, COLUMN_NAME, COLUMN_COMMENT
#     # FROM INFORMATION_SCHEMA.COLUMNS
#     # WHERE TABLE_SCHEMA = 'zentao' AND TABLE_NAME IN ({})
#     # """.format(','.join(['%s'] * len(table_names))
#     # )
#
#     sql = """
#         SELECT
#         t.TABLE_NAME,
#         t.TABLE_COMMENT,
#         c.COLUMN_NAME,
#         c.COLUMN_COMMENT,
#         k.REFERENCED_TABLE_NAME,
#         k.REFERENCED_COLUMN_NAME,
#         k.CONSTRAINT_NAME
#     FROM
#         INFORMATION_SCHEMA.TABLES t
#     JOIN
#         INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME AND t.TABLE_SCHEMA = c.TABLE_SCHEMA
#     LEFT JOIN
#         INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON c.TABLE_NAME = k.TABLE_NAME
#         AND c.COLUMN_NAME = k.COLUMN_NAME AND c.TABLE_SCHEMA = k.TABLE_SCHEMA
#         AND k.REFERENCED_TABLE_NAME IS NOT NULL
#     WHERE
#         t.TABLE_SCHEMA = 'zentao' AND t.TABLE_NAME IN ({})
#
#         """.format(','.join(['%s'] * len(table_names)))
#
#     try:
#         # 执行SQL查询
#         cursor.execute(sql, list(table_names.keys()))
#         results = cursor.fetchall()
#         # print("results:",results) #tuple  (('zt_task', 'id', '编号'), ('zt_task', 'project', '项目'),
#         dict_tem = {}
#         for table_name, table_comment, tb_colum, colum_comment, ref_table, ref_column, constraint_name in results:
#             if table_name not in dict_tem:
#                 dict_tem[table_name] = {
#                     'table_comment': table_comment,
#                     'columns': [],
#                     'foreign_keys': []
#                 }
#             dict_tem[table_name]['columns'].append(f"{tb_colum}({colum_comment})")
#             if ref_table:
#                 # dict_tem[table_name]['foreign_keys'].append({
#                 #     'constraint_name': constraint_name,
#                 #     'column_name': tb_colum,
#                 #     'referenced_table': ref_table,
#                 #     'referenced_column': ref_column
#                 # })
#                 dict_tem[table_name]['foreign_keys'].append({
#                     '字段名称': tb_colum,
#                     '引用表名': ref_table,
#                     '引用字段': ref_column
#                 })
#         print(dict_tem)
#         for key, values in dict_tem.items():
#             file.writelines(key + "（" + values["table_comment"] + "）" + '\n')
#             file.writelines('表字段：' + ','.join(values["columns"]) + '\n')
#             for dict in values["foreign_keys"]:
#                 file.writelines('表外键：' + str(dict) + '\n')
#             file.writelines('\n')
#     finally:
#         # 关闭游标和连接
#         cursor.close()
#         conn.close()
#     return dict_tem
#
# search_db()

# s = {
#   "ex_bidTeam": "存储投标任务中关联的团队成员信息，记录每个成员在投标过程中担任的职务，并通过外键关联到具体的投标任务和团队成员账户。",
#   "ex_team": "记录团队成员的基础信息，包括所属部门、公司、个人身份信息、教育背景、职称及工作年限等，同时通过外键关联到附件文件、部门及公司信息。",
#   "ex_bidSocialInsurance": "管理投标任务中团队成员的社会保险缴纳记录，包含社保缴纳的时间信息及对应的附件文件，与投标任务通过外键关联。",
#   "ex_bid": "核心投标任务表，涵盖标的名称、开标日期、招标项目基础信息及关联的项目负责人、投标人等关键数据，并通过外键关联多个附件文件与公司、团队成员信息。",
#   "ex_teamProject": "记录团队成员参与过的项目历史信息，按年份归档项目内容，通过外键与团队成员账户关联。",
#   "ex_teamQualification": "存储团队成员持有的专业资格证书信息，包含证书类型、级别、有效期及关联的附件文件，与团队成员账户通过外键绑定。",
#   "ex_bidPmProject": "关联投标任务与项目负责人历史业绩的中间表，通过外键将具体业绩记录与投标任务绑定。",
#   "ex_teamWork": "详细记录团队成员的工作履历，包括任职时间、岗位职责及担任职务，通过外键关联到团队成员账户。",
#   "ex_bidProject": "用于绑定投标任务与相关历史业绩的关联表，通过外键实现投标任务和业绩信息的双向关联。",
#   "ex_project": "全面存储项目业绩的核心信息，包含项目基础数据、合同信息、验收结果、合作方资料及关联的多类附件文件，并通过外键与公司、负责人信息联动。",
#   "ex_file": "集中管理系统内所有类型文件的元数据，记录文件的存储路径、所属对象类型及上传时间等基础信息。",
#   "ex_company": "详细记录企业工商信息、经营数据、联系方式及财务账户等全方位资料，包含企业性质、信用状况等关键属性。",
#   "ex_dept": "存储公司下属部门的组织结构信息，通过外键与所属公司主体关联。"
# }
#
# for key, value in s.items():
#     print(key)
#     print(value)
#     print('\n')

#文档解析内容
# import time
#
# import json_repair
# import os
# import re
#
# #提取标的和标包信息
# def get_bid(text):
#     #按标的切分
#     biaodi_ls = text.split('标的')
#     biaodi_ls = [i.replace("【",'[').replace("】",']') for i in biaodi_ls if i.strip()]
#
#     result = []
#
#     #获取数字的
#     pattern_num = r'\d+'
#
#     for biaodi in biaodi_ls:
#         # 获取标的数字
#         biaodi_id = re.findall(pattern_num, biaodi)[0]
#
#         if '标包' in biaodi:
#             #找出标包位置
#             pattern = r"\[(.*?)\]"
#             biaobao_str = re.findall(pattern, biaodi, re.DOTALL)[0]
#             #按标包切分
#             biaobao_ls = biaobao_str.split('标包')
#             biaobao_ls = [i for i in biaobao_ls if i.strip()]
#             for biaobao in biaobao_ls:
#                 # 获取标的数字
#                 matches = re.findall(pattern_num, biaobao)
#                 result.append(f"标的{biaodi_id}-标包{matches[0]}")
#         else:
#             #获取标的数字
#             result.append(f"标的{biaodi_id}")
#
#     return result
#
# folder = '/media/977GB/virtualbox/标包信息'
# files = os.listdir(folder)
#
# res = {}
# time.sleep(2)
# for file in files:
#     path = os.path.join(folder, file)
#
#     with open(path, 'r') as f:
#         data = json_repair.load(f)
#
#     if '详细评审标准20250408_170146' in path:
#         # with open(path,'r') as f:
#         #     text = f.read()
#         # lines = text[1:-1].split('}{')
#         # detail_review = {"详细评审标准":[]}
#         # for line in lines:
#         #     line = '{' + line + '}'
#         #     data = json_repair.loads(line)
#         #     content = list(data.values())[0]
#         #     content['适用标包列表'] = get_bid(content['适用标包'])
#         #     detail_review['详细评审标准'].append(content)
#         # res.update(detail_review)
#         res.update({"详细评审标准":data})
#     else:
#         res.update(data)

# #格式化文本
# import json_repair
# import re
#
# def json_process(data_answ):
#     pattern = r'```json(.*?)```'
#     matches = re.findall(pattern, data_answ, re.DOTALL) #抽取出内容并判断长度
#     if matches:
#         c_statement = matches[-1]
#     else:
#         c_statement=''
#     return c_statement
#
# with open('详细评审标准完善.json', 'r') as f:
#     data = json_repair.load(f)
#
# # data = data['详细评审标准']
# # # 格式化详细评审标准
# # json_format = {}
# # data = [json_repair.loads(i) for i in data]
# # s = []
# # for i in data:
# #     for key, value in i.items():
# #         if value['适用标包']:
# #             json_format[value['适用标包']] = value
# # print(len(json_format))
# # data = json_format
# # for i in data:
#
#     # print([i[:50]])
#
# # others = data.pop('其他')
# # for key, value in data.items():
# #     if isinstance(value, str):
# #         data[key] = json_repair.loads(json_process(value))
# # for other in others:
# #     data.update(json_repair.loads(json_process(other)))
#
# #格式化详细评审标准
# new_dict = {}
# for key, value in data['详细评审标准'].items():
#     if value['适用标包']:
#         answer = value.pop('适用标包列表')
#         answer = json_process(answer)
#         if "json" in answer:
#             answer = json_process(answer)
#         list_s1=answer.replace("\n",'').replace(" ",'').replace("\"",'')[1:-1].split(',')
#         for l_i in list_s1:
#             if l_i in new_dict:
#                 print(f'error\t{[l_i]}\t{answer}')
#
#             new_dict[l_i] = value
#
# import json_repair
# import json
# import time
# import re
#
# st = time.time()
#
# #读取结果
# with open('/media/977GB/wcj_work/禅道/新视图开发/zentao/bid/generate/第六次/json化结果.json', 'r') as f:
#     bid_parse_res = json_repair.load(f)
#
# #标的清单及分包情况/项目概况和招标范围，转为列表
# data = bid_parse_res.pop('标的清单及分包情况/招标范围')
# data_dict = {}
# for value in data:
#     ls = []
#     for sub_value in value['包括的标包为']:
#         if not ls:
#             ls.append(list(sub_value.keys()))
#         ls.append(list(sub_value.values()))
#     data_dict[value['标的名称']] = ls
# bid_parse_res['标的清单及分包情况/招标范围'] = data_dict
#
# # 合并通用资格要求和专用资格要求
# data1 = bid_parse_res.pop('通用资格要求')
# data2 = bid_parse_res.pop('专用资格要求')
#
# #专用资格要求处理
# res = {}
# for value in data2:
#     sub_value = value.pop('关联标的/标包/标段')
#     res[sub_value] = list(value.values())[0]
# bid_parse_res['资格要求'] = {
#     "通用资格要求": data1,
#     "专用资格要求": res
# }
#
# #初步评审标准，转为列表
# data = bid_parse_res.pop('初步评审标准')
# ls = []
# for value in data:
#     if not ls:
#         ls.append(list(value.keys()))
#     ls.append(list(value.values()))
# bid_parse_res['初步评审标准'] = {'初步评审标准':ls}
#
# #只需要表格展示的详细评审标准
# data = bid_parse_res.pop('详细评审标准-表格展示')
# bid_parse_res.pop('详细评审标准')
# bid_parse_res['详细评审标准'] = data
#
# #将分值构成和中标推荐原则转为三层结构
# data = bid_parse_res.pop('分值构成')
# ls = []
# for value in data:
#     if not ls:
#         ls.append(list(value.keys()))
#     ls.append(list(value.values()))
# bid_parse_res['分值构成'] = {'分值构成':ls}
#
# data = bid_parse_res.pop('中标推荐原则')
# ls = []
# for value in data:
#     if not ls:
#         ls.append(list(value.keys()))
#     ls.append(list(value.values()))
# bid_parse_res['中标推荐原则'] = {'中标推荐原则':ls}
#
# #投标人须知前附表转为三层结构
# data = bid_parse_res.pop('投标人须知前附表')
# ls = []
# for value in data:
#     if not ls:
#         ls.append(list(value.keys()))
#     ls.append(list(value.values()))
# bid_parse_res['投标人须知前附表'] = {'投标人须知前附表':ls}
#
# #其他额外信息转为三层结构
# data = bid_parse_res.pop('其他额外信息')
# #更新
# bid_parse_res.update(data)
#
# #无效标与废标项
# data = bid_parse_res.pop('无效标与废标项')
# res = {}
# for i, value in enumerate(data, start=1):
#     res[f"情况{i}"] = value
# bid_parse_res['无效标与废标项'] = {'无效标与废标项':res}
#
# #将json格式化为3层结构
# #第一层（横标题）改为列表结构
# first_ls = []
#
# for key, value in bid_parse_res.items():
#
#     #第二层（竖标题）改为列表
#     second_ls = []
#
#     for sub_key, sub_value in value.items():
#
#         # 第三层（内容）改为列表
#         third_ls = []
#         if isinstance(sub_value, dict):
#             for title, content in sub_value.items():
#                 content_type = 'table' if isinstance(content, list) else 'string'
#                 third_ls.append({"title": title, "content": content, "content_type": content_type})
#         else:
#             content_type = 'table' if isinstance(sub_value, list) else 'string'
#             third_ls.append({"content": sub_value, "content_type": content_type})
#
#         # bid_parse_res[key][sub_key] = res
#         second_ls.append({"title": sub_key, "content": third_ls})
#
#     first_ls.append({"title": key, "content": second_ls})
#
# print(time.time()-st)
# print(len(json.dumps(first_ls,ensure_ascii=False)))
#
# with open('前端返回结果1.json', 'w') as f:
#     json.dump(first_ls, f, ensure_ascii=False)
# import json
# import uuid
# import random
#
# # def build_tree(data, level=1, parent_id=[], order={}):
# #
# #     if len(data) > 0:
# #         for data_dict in data:
# #             for key, value in data_dict.items():
# #                 number = random.randint(1, 100000)
# #
# #                 #级别序号区别开
# #                 parent_id = parent_id[:level-1] + [str(number)]
# #                 path = ','.join(parent_id)
# #
# #                 #添加该层级标题顺序
# #                 if str(parent_id[:level-1]) not in order:
# #                     order[str(parent_id[:level-1])] = 0
# #                 else:
# #                     order[str(parent_id[:level - 1])] += 1
# #
# #                 print(path,order[str(parent_id[:level - 1])], key)
# #
# #                 #传入父路径
# #                 build_tree(value, level+1, parent_id, order)
# #
# #     return order
#
#
# #
# from docx import Document
#
# doc = Document('/media/977GB/wcj_work/禅道/新视图开发/zentao/bid/文档/商务文件模板/7_投标人重要信息情况表_标的1：业务系统2024年第五批采购项目.docx')
#
# table = doc.tables[0]
#
# ls = []
#
# for row in table.rows:
#     row_ls = []
#     cells = row.cells
#     for i,cell in enumerate(cells):
#         if cell not in cells[:i]:
#             row_ls.append(cell.text)
#
#     #如果该行没有空值，则认为该行为横向标题行
#     if '' not in row_ls:
#         row_ls[0] = '标题：'+row_ls[0]
#     ls.append(row_ls)
#
# print(ls)
#
#
# {"姓名": "王五", "性别": "男", "语文": 95, "数学": 88, "评价": "优"}

# import pymysql
# import json
#
# # 数据库连接配置
# db_config = {
#     'host': 'localhost',
#     'user': 'root',
#     'password': '123456',
#     'database': 'zentao',
#     'charset': 'utf8mb4'
# }
#
# def get_first_row_with_comments_as_keys():
#     connection = pymysql.connect(**db_config)
#     try:
#         with connection.cursor() as cursor:
#             # 查询表的第一条数据
#             sql = "SELECT * FROM ex_company LIMIT 1"
#             cursor.execute(sql)
#             row = cursor.fetchone()
#
#             # 查询字段和注释信息
#             cursor.execute("SHOW FULL COLUMNS FROM ex_company")
#             columns_info = cursor.fetchall()
#
#             # 构建字段名到注释的映射
#             column_name_to_comment = {
#                 col[0]: col[8] or col[0] for col in columns_info
#             }
#
#             # 将行数据转换为以注释为 key 的字典
#             result = {}
#             for col_name, value in zip(column_name_to_comment, row):
#                 comment = column_name_to_comment.get(col_name, col_name)
#                 result[comment] = value
#
#             # 转为 JSON 字符串
#             return json.dumps(result, ensure_ascii=False, indent=2)
#
#     finally:
#         connection.close()
#
# # 调用函数并打印结果
# json_output = get_first_row_with_comments_as_keys()
# print(json_output)


# from docx import Document
#
# doc = Document('/media/977GB/wcj_work/禅道/新视图开发/zentao/bid/文档/DOCX 文档.docx')
#
# table = doc.tables[0]
#
# ls = []
#
# for row in table.rows:
#     row_ls = []
#     for cell in row.cells:
#         row_ls.append(cell.text)
#     ls.append(row_ls)
#
# title = ls[0]
# res = []
# avg = []
# for row in ls[1:-1]:
#     if not avg:
#         avg = [float(i) for i in row[1:]]
#     else:
#         avg = [i+float(j) for i,j in zip(avg,row[1:])]
#     mid = {}
#     for key, value in zip(title,row):
#         mid[key.replace('\n','')] = value
#
#     res.append(mid)
# l = len(ls[1:-1])
# avg = ['平均值'] + [i/l for i in avg]
#
# mid = {}
# for key, value in zip(title,avg):
#     mid[key.replace('\n','')] = value
#
# res.append(mid)
# print(res)

# title = ['直接上级控股/管理单位/自然人控股股东名称', '对本单位的控股（出资）比例（%）', '单位负责人', '联系人及电话', '单位地址']
# values = ['南方电网数字电网研究院股份有限公司',
#  '100%',
#  '林火华',
#  '蔡霖\n020-32657063',
#  '广州市黄埔区中新广州知识城亿创街 1 号 406 房之86']
# res = {"直接上级控股/管理单位/自然人控股股东": []}
# mid = {}
# for key, value in zip(title, values):
#     mid[key] = value
# res['直接上级控股/管理单位/自然人控股股东'].append(mid)
#
# title = ['直接下级控股/管理单位名称', '本单位控股（出资）比例（%）', '单位负责人', '联系人及电话', '单位地址']
# values = ['无'] * 5
#
# mid = {}
# res["直接下级控股/管理单位名称"]= []
# for key, value in zip(title, values):
#     mid[key] = value
# res['直接下级控股/管理单位名称'].append(mid)
#
# print(res)

# #在指定位置添加一行
# def insert_row(table, row_index):
#
#     # 在指定位置插入一行
#     table.add_row()
#
#     # 移动新插入的行到指定位置
#     rows = table.rows
#     rows[row_index]._element.getparent().insert(
#         rows[row_index]._element.getparent().index(rows[row_index]._element), rows[-1]._element
#     )
#     rows[-1]._element.getparent().remove(rows[-1]._element)
#
#     return table
#
# #docx添加内容
# def docx_add(table, result, save_path):
#     from docx import Document
#     from docx.oxml.ns import qn
#
#     table_rows = table.rows
#     table_row_index = 0
#     data_row_index = 0
#     while data_row_index < len(result):
#
#         data_row = result[data_row_index]
#         print(data_row)
#
#         # 在末尾添加一行新的行
#         if table_row_index >= len(table_rows):
#             print(len(table_rows))
#             table.add_row()
#             # 更新table和cells
#             table_rows = table.rows
#             print(len(table_rows))
#             continue
#
#         # 获取该行第一个单元格的内容
#         first_cell_text = table_rows[table_row_index].cells[0].text
#
#         # 如果内容不为标题但是该单元格有内容不为省略号并且单元格内容和填充内容不同，则代表该行需要新增一行
#         if not data_row[0].startswith('标题：') and first_cell_text and first_cell_text != data_row[0] and first_cell_text!='……':
#             table = insert_row(table, table_row_index)
#             # 更新table和cells
#             table_rows = table.rows
#             continue
#         else:
#             cells = table_rows[table_row_index].cells
#
#         # 先遍历该行，判断是否为空分割行
#         ls = []
#         for j, cell in enumerate(cells):
#             if cell not in cells[:j]:
#                 ls.append(cell.text)
#
#         # 如果该行为空分割行，则跳到表格下一行
#         if len(ls) == 1 and not ls[0]:
#             # 内容不为标题，则新增一行
#             if not data_row[0].startswith('标题：'):
#                 table = insert_row(table, table_row_index)
#                 # 更新table和cells
#                 table_rows = table.rows
#                 continue
#             else:
#                 table_row_index += 1
#                 continue
#
#         # 查找标题所在的行
#         if data_row[0].startswith('标题：') and (not first_cell_text or first_cell_text == '……'):
#             # 删除该行
#             # 获取底层 XML 元素
#             tr = table.rows[table_row_index]._element
#             # 从表格中移除该行
#             tr.getparent().remove(tr)
#             # 更新table和cells
#             table_rows = table.rows
#             continue
#
#         for j, text in enumerate(data_row):
#             # 如果单元格为空或者未省略号，则填充
#             if not cells[j].text or cells[j].text == '……':
#                 # cells[j].text = text
#
#                 # 如果单元格内已有段落，则获取；否则添加一个新的段落
#                 if cells[j].paragraphs:
#                     paragraph = cells[j].paragraphs[0]
#                 else:
#                     paragraph = cells[j].add_paragraph()
#
#                 paragraph.text = text
#                 run = paragraph.runs[0]
#
#                 # 字体样式为宋体5号字
#                 run.font.name = '宋体'
#                 run._element.rPr.rFonts.set(qn('w:eastAsia'), run.font.name)
#
#         # 下一行数据
#         data_row_index += 1
#         table_row_index += 1
#
#     # 删除多余的空行
#     if table_row_index < len(table_rows):
#         # 获取该行第一个单元格的内容
#         first_cell_text = table_rows[table_row_index].cells[0].text
#         if first_cell_text == '……' or not first_cell_text:
#             # 获取底层 XML 元素
#             tr = table.rows[table_row_index]._element
#             # 从表格中移除该行
#             tr.getparent().remove(tr)
#             # 更新table和cells
#             table_rows = table.rows
#
#     doc.save(save_path)
#     return table
#
# #填充7_投标人重要信息情况表_标的1：业务系统2024年第五批采购项目.docx
# path = '/media/977GB/wcj_work/禅道/新视图开发/zentao/bid/文档/商务文件模板/7_投标人重要信息情况表_标的1：业务系统2024年第五批采购项目.docx'
# doc = Document(path)
# table = doc.tables[0]
# result = [["标题：项目", "南方电网公司2024年第八批信息化项目"], ["标的", "标的2：数字化技术平台2024年第五批采购项目"], ["标包", "标包1：北斗运营服务应用V3.0（安全升级改造）建设项目"], ["标题：序号", "投标人名称", "质量", "服务期/交货期", "项目负责人姓名", "项目负责人相关证书名称及编号"], ["1", "南方电网数字企业科技(广东)有限公司", "无质量问题", "1、9个月\n2、6个月", "肖建毅", "1.PMP\n2.测试\n3.222"]]
#
# docx_add(table, result, '1111.docx')
#
# # 填充8_商务_投标人关联企业情况声明.docx
# path = '/media/977GB/wcj_work/禅道/新视图开发/zentao/bid/文档/商务文件模板/8_商务_投标人关联企业情况声明.docx'
# doc = Document(path)
# table = doc.tables[0]
# result = [
#     ["标题：直接上级控股/管理单位/自然人控股股东名称", "对本单位的控股（出资）比例（%）", "单位负责人", "联系人及电话", "单位地址"],
#     ["南方电网数字电网研究院股份有限公司", "100%", "林火华", "蔡霖\n020-32657063", "广州市黄埔区中新广州知识城亿创街 1 号 406 房之86"],
#     ["A公司", "98%", "aaa", "张三\n020-1111111", "深圳市"],
#     ["A公司", "98%", "aaa", "张三\n020-1111111", "深圳市"],
#     ["A公司", "98%", "aaa", "张三\n020-1111111", "深圳市"],
#     ["标题：直接下级控股/管理单位名称", "本单位控股（出资）比例（%）", "单位负责人", "联系人及电话", "单位地址"],
#     ["无", "无", "无", "无", "无"],
#     ["无", "无", "无", "无", "无"],
#     ["无", "无", "无", "无", "无"]
# ]
#
# docx_add(table, result, '2222.docx')
#
# #
# path = '/media/977GB/wcj_work/禅道/新视图开发/zentao/bid/文档/商务文件模板/6_商务_投标人基本情况表.docx'
# doc = Document(path)
# table = doc.tables[0]
# result = [["投标人名称", "南方电网数字企业科技(广东)有限公司", "曾用名", "①广东省电力通信有限公司 ②广东省电力信息通信有限公司 ③广东电力信息科技有限公司"], ["企业性质", "国有企业", "注册地址", "广州市越秀区东风东路 836 号 1 座 2802 房 (不可作厂房使用)"], ["证书", "", "总人数（技术人员数）", "261（200）"], ["法定代表人（单位负责人）", "caoxu", "联系电话", "020-85737461"], ["联系人", "xiehengrui", "电话/手机", "13609782303"], ["传真", "", "电子信箱", "xierh@csg.cn"], ["企业网址", "", "邮政编码", "510075"], ["统一社会信用代码", "91440000231116983C", "纳税人识别号", "91440000231116983C"], ["基本账户开户行", "中国建设银行股份有限公司广州广电支行", "基本账户账号", "44001403304050092910"], ["信用状况", "A级", "其他", ""]]
# source_table = docx_add(table, result, '3333.docx')
#
#
# hj_data = [
#                            ['1', '党政机要密码科学技术奖', '国家级', '三等奖', '中共中央办公厅'],
#                            ['2', '广西科学技术奖', '省部级', '二等奖', '广西壮族自治区人民政府'],
#                             ['3', '第二届中国工业互联网大赛-基于工业互联网的新型智慧用能解决方案', '省部级', '三等奖', '深圳市工业和信息化局/深圳市龙华区人民政府'],
#                             ['4', '中国南方电网公司价值创造奖-智慧能源工业互联网平台', '省部级', '三等奖', '中国南方电网公司'],
#                             ['5', '2023年电力科技创新奖—电网企业全员本质安全能力提升“数智”赋能关键技术研究与应用', '行业协会', '一等奖', '中国电力企业联合会'],
#                              ['6', '2023年电力科技创新奖—基于源头预防的现场作业“三统一”透明管控方法研究与实践', '行业协会', '一等奖', '中国电力企业联合会'],
#                              ['7', '2021年度电力科技创新奖-面向人机协同作业的变电机器人装备及体系研究', '行业协会', '二等奖', '中国电力企业联合会'],
#                               ['8', '2020年度电力科技创新奖-全栈国产化关键技术在电力系统设备智慧监测的创新研究与应用', '行业协会', '科技创新奖', '中国电力企业联合会'],
#                                ['9', '2021深圳软件行业推荐优秀产品-燃点大数据服务平台', '行业协会', '推荐优秀产品', '深圳市软件行业协会'],
#                                 ['10', '2021深圳软件行业推荐优秀产品-智慧能源工业互联网平台', '行业协会', '推荐优秀产品', '深圳市软件行业协会'],
#                                 ['11', '“云燕”数字化工程全过程管理平台入选“首届红数麟杯数字化创新大赛百强成果”', '行业协会', '百强成果', '大湾区中央企业数字化协同创新联盟'],
#            ['', '2023年（第六届）电力信息通信新技术大会暨数字化发展论坛新型电力系统数字技术卓越案例-面向全栈自主可控的电力云原生适配工程方法论及创新实践', '行业协会', '卓越案例', '中国电力企业联合会科技开发服务中心'],
#             ['', '2021年（第四届）电力信息新技术大会暨数字化国际高峰论坛优秀案例《城市配电网网格化规划数字转型探索及实践》', '行业协会', '优秀案例', '中国电力企业联合会科技开发服务中心'],
#             ['', '2023年工业互联网融合创新应用电力行业优秀案例-云燕平台数字化设计创新应用', '行业协会', '优秀案例', '中国电力发展促进会'],
#              ['', '行业云平台领航者优秀案例一云多芯项目', '行业协会', '优秀案例', '中国信息通信研究院']]
#
# for i in hj_data:
#     print(i)

# #添加标题
# def add_tree_to_doc(data, numbering=None):
#     """
#     递归将树结构写入 docx，并加上编号：1., 1.1., 1.1.1 等
#     :param doc: python-docx 的 Document 对象
#     :param data: 当前层级的列表数据
#     :param numbering: 当前编号路径，例如 [1], [1,1]
#     """
#     if numbering is None:
#         numbering = []
#
#     for idx, item in enumerate(data):
#         current_numbering = numbering + [idx + 1]  # 编号从 1 开始
#         number_str = ".".join(map(str, current_numbering)) + "."
#
#         # 添加带编号的段落
#         print(f"Heading {len(current_numbering)}", f"{number_str} {item['title']}")
#
#         # 递归处理子级
#         if item.get("children"):
#             add_tree_to_doc(item["children"], current_numbering)
#
# ls = [
#   {
#     "title": "发明专利",
#     "path": "",
#     "children": [
#       {
#         "title": "一种业务域数据的管理方法及装置",
#         "path": "source/company/patent/南方电网数字平台科技（广东）有限公司/发明专利/一种业务域数据的管理方法及装置.pdf",
#         "children": [
#           {
#             "title": "一种业务域数据的管理方法及装置",
#             "path": "source/company/patent/南方电网数字平台科技（广东）有限公司/发明专利/一种业务域数据的管理方法及装置.pdf",
#             "children": [
#               {
#                 "title": "一种业务域数据的管理方法及装置",
#                 "path": "source/company/patent/南方电网数字平台科技（广东）有限公司/发明专利/一种业务域数据的管理方法及装置.pdf",
#                 "children": [{
#                 "title": "一种业务域数据的管理方法及装置",
#                 "path": "source/company/patent/南方电网数字平台科技（广东）有限公司/发明专利/一种业务域数据的管理方法及装置.pdf",
#                 "children": []
#               }]
#               },
#                 {
#                 "title": "一种业务域数据的管理方法及装置",
#                 "path": "source/company/patent/南方电网数字平台科技（广东）有限公司/发明专利/一种业务域数据的管理方法及装置.pdf",
#                 "children": []
#               }
#             ]
#           },
# {
#                 "title": "一种业务域数据的管理方法及装置",
#                 "path": "source/company/patent/南方电网数字平台科技（广东）有限公司/发明专利/一种业务域数据的管理方法及装置.pdf",
#                 "children": []
#               }
#         ]
#       }
#     ]
#   },
#   {
#     "title": "软件著作权",
#     "path": "",
#     "children": [
#       {
#         "title": "IT资产管理系统V1.0",
#         "path": "source/company/software/南方电网数字平台科技（广东）有限公司/IT资产管理系统V1.0.png",
#         "children": []
#       }
#     ]
#   }
# ]
#
# add_tree_to_doc(ls,[17])

from docx import Document

#修改第一段
doc = Document('/media/977GB/wcj_work/投标文件生成/data/generate/project/业绩生成_20250417_025442.docx')

#如果需要替换第一段
first_paragraph = doc.paragraphs[0]
print([first_paragraph.text])
first_paragraph.clear()
run = first_paragraph.add_run('你是谁')
run.bold = False
print([first_paragraph.text])
# run.font.size = Pt(14)
# # 设置字体为宋体
# run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
# run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
# first_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
# first_paragraph.paragraph_format.line_spacing = 1.5  # 设置行间距为1.5倍
# first_paragraph.paragraph_format.first_line_indent = Pt(24)  # 设置首行缩进为2个字符（大约24磅）
# first_paragraph.paragraph_format.space_before = Pt(13)  # 设置段前间距为13磅
